package cn.crc.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Formatter;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9876);
        byte[] receiveData = new byte[1024];

        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);
            String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("RECEIVED: " + message);
            // 可以选择在这里将数据转换为16进制并发送回去

            message+= "恭喜发财";
            String hexMessage = bytesToHex(message.getBytes());//String hexMessage = bytesToHex(message);
            byte[] sendData = hexMessage.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
            socket.send(sendPacket);
        }
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));//sb.append(String.format("%X ", b));
        }
        return sb.toString();
    }
    public static String bytesToHex(String str) {
        Formatter formatter = new Formatter();
        String hexString = formatter.format("%x", str).toString(); // 对于整数使用"%x"格式化，对于长整数使用"%X"（大写）或"%x"（小写）
        System.out.println("Hex String: " + hexString);
        formatter.close(); // 关闭Formatter对象，释放资源。
        return hexString;
    }
}
